package com.xyt.imei.core.util;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.google.gson.Gson;
import com.luminary.common.framework.core.properties.MetaProperties;
import com.xyt.imei.core.meta.CacheKey;
import com.xyt.imei.core.meta.ServerInfo;
import com.xyt.imei.core.model.po.User;

@Component
public class TokenUtil {

	@Autowired
	private MetaProperties metaProperties;
	
	@Autowired
	private RedisTemplate<String, String> redisTemplate;
	
	public String getToken() {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		return request.getHeader(metaProperties.getTokenHeaderParam());
	}
	
	public User getUser() {
		Gson gson = new Gson();
		String json = redisTemplate.opsForValue().get(ServerInfo.CACHE_PREFIX + "_" + CacheKey.TOKEN + "_" + getToken());
		User user = gson.fromJson(json, User.class);
		return user;
	}
	
	public User getUser(String token) {
		Gson gson = new Gson();
		String json = redisTemplate.opsForValue().get(ServerInfo.CACHE_PREFIX + "_" + CacheKey.TOKEN + "_" + token);
		User user = gson.fromJson(json, User.class);
		return user;
	}
	
}
